﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace QQ2564874169.Core.Utils
{
    public static class ModelHelper
    {
        public static void Keep<T>(IEnumerable<T> models, params Expression<Func<T, object>>[] exprs)
        {
            if (models == null)
                return;

            var names = new List<string>();
            foreach (var item in exprs)
            {
                var member = item.Body as MemberExpression;
                var unary = item.Body as UnaryExpression;
                member = member ?? unary?.Operand as MemberExpression;
                if (member != null)
                    names.Add(member.Member.Name);
            }

            Clear(models, names.ToArray(), true);
        }

        public static void Exclude<T>(IEnumerable<T> models, params Expression<Func<T, object>>[] exprs)
        {
            if (models == null)
                return;

            var names = new List<string>();
            foreach (var item in exprs)
            {
                var body = item.Body as MemberExpression;
                if (body != null)
                    names.Add(body.Member.Name);
            }
            Clear(models, names.ToArray(), false);
        }

        private static void Clear<T>(IEnumerable<T> models, string[] names, bool isKeep)
        {
            var ps = typeof(T).GetProperties();

            var enumerable = models as T[] ?? models.ToArray();

            foreach (var item in ps)
            {
                if (isKeep == names.Contains(item.Name))
                    continue;

                foreach (var model in enumerable)
                {
                    item.SetValue(model, item.PropertyType.GetDefaultValue(), null);
                }
            }
        }
    }
}
